import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/media_urgent_response_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_detail_update.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_urgent_update.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/update_terminal_play_list_status_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_view_model.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/mixin/user_stream_mixin.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_diy_page_event.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/pages/check_in_statistics_list_widget.dart';
import 'package:e_reception_flutter/ui/index/bean/index_bind_termainal_info.dart';
import 'package:e_reception_flutter/ui/index/even/clear_index_company_info_event.dart';
import 'package:e_reception_flutter/ui/index/even/location_changed_event.dart';
import 'package:e_reception_flutter/ui/index/widgets/index_grid_terminal_widget.dart';
import 'package:e_reception_flutter/ui/index/widgets/index_guidancenotes_widget.dart';
import 'package:e_reception_flutter/ui/index/widgets/index_horizontal_vertical_play_list_widget.dart';
import 'package:e_reception_flutter/ui/index/widgets/index_top_company_and_logo_widget.dart';
import 'package:e_reception_flutter/ui/index_nav/even/index_refresh_even.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/play_file_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/terminal_info_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/terminal_number_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/common_terminal_settings_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/set_terminal_state_type.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/event/terminal_list_refresh_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/event/terminal_volume_refresh_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/set_terminal_status_menu_dialog.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/bean/terminal_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/single_terminal_manage_page.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_index_event.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import 'bean/index_top_base_info.dart';
import 'bean/index_top_info_response_bean.dart';
import 'index_view_model.dart';
import 'widgets/index_manage_terminal_title_widget.dart';
import 'widgets/index_statistics_card_widget.dart';

/// 首页
///
/// @author: zengxiangxi
/// @createTime: 1/5/21 4:18 PM
/// @specialDemand:
class IndexPage extends StatefulWidget {
  static const String ROUTER = "IndexPage";
  static const String AUTO_LOGIN_TIME = "auto_login_time";

  IndexPage({Key key}) : super(key: key);

  @override
  _IndexPageState createState() => _IndexPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult(context, IndexPage(),
        routeName: IndexPage.ROUTER);
  }
}

class _IndexPageState extends BaseState<IndexPage>
    with NavigatorPageMixin, UserStreamMixin {
  IndexViewModel _viewModel;
  MediaLibraryIndexViewModel _urgentViewModel;
  NewTerminalListViewModel _terminalListViewModel;
  UserDataBean _user;

  bool isShowTips;

  StreamSubscription _streamSubscription;
  StreamSubscription _userSubscription;

  // StreamSubscription _attendanceStreamSubscription;

  StreamSubscription _returnPageStreamSubscription;

  StreamSubscription _terminalNumRefreshSubscription;

  // StreamSubscription _homePageWidgetSubscription;

  StreamSubscription _clearIndexCompanyInfoSubscription;

  int _selectedIndex = 0;

  ScrollController _horizontalController;

  VgLocation _locationPlugin;

  StreamSubscription<ConnectivityResult> _netSubscription;
  //网络发生变化前，网络的状态
  bool _networkFlg = true;
  ValueNotifier<int> _initPageNotifier;

  StreamSubscription homePageInterfaceEventMonitor;
  //00不显示代表已经更新到 01显示
  String _showTerminalStatus = "00";
  String _hintHsn = "";


  networkRecoverAndDoSomeRefresh(){
    //之前网络的状态为无网络，并且网络状态变好了
    if(!_networkFlg){
      // _viewModel.getTopInfoHttp(_selectedIndex);
      //之前是两个接口
      // _viewModel.getHomePunchInfo();
      // _viewModel.getHomeTerInfo(_selectedIndex, gps: _latestGps);
      //现在是合并接口
      // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
      // _viewModel.getHomeBaseInfo();
      _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "networkRecoverAndDoSomeRefresh");
      _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
      _viewModel.getUrgent();
    }
    _networkFlg = true;
  }

//网络初始状态
  connectivityInitState() {
    _netSubscription =
        Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
          print('netStatus' + result.toString());
          if(result == ConnectivityResult.none){
            _networkFlg = false;
          }else if(result == ConnectivityResult.mobile){
            networkRecoverAndDoSomeRefresh();
          }else if(result == ConnectivityResult.wifi){
            networkRecoverAndDoSomeRefresh();
          }
        });
  }

  // Timer _timer;
  // double _value = 0;

  bool showLoad;

  // IndexTopPunchInfo punchInfo;
  // IndexTopBaseInfo baseInfo;
  IndexBindTermainalInfo _topInfo;

  TerminalDetailResponseBean _terminalDetailResponseBean;
  // static const String INDEX_TOP_INFO_API = NetApi.BASE_URL + "app/appTerminalManageHome";
  String _latestGps;
  String _punchAndTerminalInfoCacheKey;
  @override
  void initState() {
    super.initState();
    // punchInfo = IndexTopPunchInfo();
    // baseInfo = IndexTopBaseInfo();
    showLoad = true;
    _viewModel = IndexViewModel(this);
    //获取首页企业信息以及打卡信息
    _viewModel.getHomeCompanyBaseInfoAndPunchInfo();

    _punchAndTerminalInfoCacheKey = UserRepository.getInstance().getHomePunchAndTerminalInfoCacheKey();
    Future<String> latlng = VgLocationUtils.getCacheLatLngString();
    latlng.then((value){
      print("缓存gps:" + value);
      _latestGps = value;
      // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: value);
      _viewModel.getHomeTerminalInfo(_selectedIndex, gps: value);
    });
    MediaLibraryIndexViewModel.EMPTY_FLAG = false;
    _urgentViewModel = MediaLibraryIndexViewModel(this);
    _terminalListViewModel = NewTerminalListViewModel(this);

    // _viewModel?.indexTopPunchInfoValueNotifier?.addListener(() {
    //   punchInfo = _viewModel?.indexTopPunchInfoValueNotifier?.value;
    //   setState(() { });
    // });
    //
    // _viewModel?.indexTopBaseValueNotifier?.addListener(() {
    //   baseInfo = _viewModel?.indexTopBaseValueNotifier?.value;
    //   setState(() { });
    // });


    _locationPlugin = VgLocation();
    _locationPlugin.requestSingleLocation((data) {
      if(data.containsKey("latitude") && data.containsKey("longitude")){
        LatLngBean latLngBean = LatLngBean.fromMap(data);
        String gps = latLngBean.latitude.toString() + "," + latLngBean.longitude.toString();
        print("获取到了最新gps:" + gps);
        _viewModel.getHomeTerminalInfo(_selectedIndex, gps: gps);
        // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: gps);
        // _viewModel.getHomeBaseInfo();
      }
    });
    VgEventBus.global.streamController.stream.listen((event) {
      if (event is LocationChangedEvent) {
        print("收到gps更新的:" + event?.gps);
        if(StringUtils.isNotEmpty(event?.gps??"")){
          if(event?.gps == _latestGps){
            print("更新的gps与当前一致，不执行刷新");
            return;
          }
          _latestGps = event?.gps;
          //现在是合并接口
          // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
          // _viewModel.getHomeBaseInfo();
          _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
        }
      }
    });
    homePageInterfaceEventMonitor = VgEventBus.global.on<HomePageInterfaceEventMonitor>().listen((event) {
      showLoad = event?.showLoad;
      setState(() {});
    });

    _initPageNotifier = new ValueNotifier(_selectedIndex);

    connectivityInitState();
    // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
    // _viewModel.getHomeBaseInfo();
    //获取终端信息
    _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
    _viewModel.getInitTerminalInfoAndPlayList(gps: _latestGps);

    _viewModel.getUrgent();
    _horizontalController= ScrollController();
    addPageListener(
      onPop: () {
        // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
        // _viewModel.getHomeBaseInfo();
        _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
        _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "addPageListener onPop");
        _viewModel?.getUrgent();
      },
    );
    // _userSubscription = UserRepository.getInstance().userStream?.listen((UserDataBean userBean) {
    //   print("收到用户信息变化的回调");
    //   _viewModel.getHomeBaseInfo();
    //   _viewModel.getHomePunchInfo();
    //   _viewModel.getHomeTerInfo(_selectedIndex, gps: _latestGps);
    //   VgEventBus.global.send(new MediaLibraryRefreshEven());
    //   setState(() { _selectedIndex = 0;});
    // });
    addUserStreamListen((value) {
      Future.delayed(Duration(milliseconds: 50), (){
        print("收到用户信息变化的回调");
        // _viewModel.getHomeBaseInfo(authId: value?.authId);
        // //现在是合并接口
        // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps, authId: value?.authId);
        if(UserRepository.getInstance().isSmartHomeCompany()){
          return;
        }
        if(value.isColdLogin??false){
          print("收到用户信息变化的回调，来自新登录，不执行后续操作");
          return;
        }
        _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(authId: value?.authId, hideShowLoad: true, from: "收到用户信息变化的回调");
        _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps, authId: value?.authId);
        setState(() { _selectedIndex = 0;});
        _viewModel.getUrgent();

      });
      // _viewModel?.getTopInfoHttp(_selectedIndex);
    });
    _streamSubscription =
        VgEventBus.global.on<IndexRefreshEven>().listen((event) {
          if (event is! IndexRefreshEven) {
            return;
          }
          if(StringUtils.isNotEmpty(event.hsn)){
            String hsn = event.hsn;
            if(_topInfo != null && _topInfo?.data?.bindTerminalList!= null
                && hsn != _topInfo?.data?.bindTerminalList[_selectedIndex]?.hsn){
              //不做刷新
            }else{
              // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
              // _viewModel.getHomeBaseInfo();
              _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "_streamSubscription0");
              _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
            }
          }else{

            // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
            // _viewModel.getHomeBaseInfo();
            _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "_streamSubscription1");
            _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
            _viewModel.getUrgent();
          }

        });

    // _attendanceStreamSubscription = VgEventBus.global.on<ArtificialAttendanceUpdateEvent>().listen((event) {
    //   _viewModel.getTopInfoHttp(_selectedIndex);
    // });

    _returnPageStreamSubscription = VgEventBus.global.on<MonitoringIndexPageClass>().listen((event) {
      // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
      // _viewModel.getHomeBaseInfo();

      _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "_returnPageStreamSubscription");
      _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
    });

    // _homePageWidgetSubscription = VgEventBus.global.on<UpdateHomePageEventMonitor>().listen((event) {
    //   showLoad = true;
    // });


    _terminalNumRefreshSubscription = VgEventBus.global.streamController.stream.listen((event) {
      if (event is PlayFileUpdateEvent
          || event is MediaLibraryRefreshEven
          || event is MediaDetailUpdateEvent
          || event is TerminalVolumeRefreshEvent
          || event is TerminalListRefreshEvent
          || event is TerminalInfoUpdateEvent
          || event is RefreshSmartHomeIndexEvent
          || event is RefreshDiyPageEvent
      ) {
        if(event is MediaLibraryRefreshEven){
          setState(() {
            if((_topInfo?.data?.bindTerminalList?.length??0) > _selectedIndex){
              _showTerminalStatus = "00";
              if(StringUtils.isNotEmpty(_topInfo?.data?.bindTerminalList[_selectedIndex]?.hsn??"")){
                _hintHsn = _topInfo?.data?.bindTerminalList[_selectedIndex]?.hsn;
              }
            }
          });
        }
        _viewModel.getUrgent();
        if(event is TerminalVolumeRefreshEvent || event is TerminalListRefreshEvent || (event is RefreshDiyPageEvent && (event?.isDelete??false))){
          // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps, hideShowLoad: true);
          // _viewModel.getHomeBaseInfo();
          _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps,);
          _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet( hideShowLoad: true);
        }else{
          // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
          // _viewModel.getHomeBaseInfo();
          _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps,);
          _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "_terminalNumRefreshSubscription");
        }


      }
      if(event is TerminalNumberUpdateEvent){
        setState(() { _selectedIndex = 0;});
        // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps, unbindHsn: event?.hsn);
        // _viewModel.getHomeBaseInfo();
        _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps, unbindHsn: event?.hsn);
        _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "event is TerminalNumberUpdateEvent");
      }
      if(event is MediaUrgentUpdateEvent){
        _viewModel.getUrgent();
        // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
        // _viewModel.getHomeBaseInfo();
        _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
        _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "event is MediaUrgentUpdateEvent");
      }
      if(event is UpdateTerminalPlayListStatusEvent){
        setState(() {
          _showTerminalStatus = event.obtainflg;
          _hintHsn = event.hsn??"";
        });
      }
      if(event is ClearIndexCompanyInfoEvent){
        print("收到清空首页信息的指令:" + (event.getCache??false).toString());
        if(event.getCache??false){
          // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
          // _viewModel.getHomeBaseInfo();
          _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
          _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "event is ClearIndexCompanyInfoEvent");
        }else{
          _viewModel.clearHomePunchInfoCache();
          _viewModel.clearHomeTerInfo();
          _viewModel.clearHomeBaseInfoCache();
        }
      }
      // _value = 0;
    });

    _getSPValue();
    // _viewModel?.topInfoValueNotifier?.addListener(() {
    //   showLoad = true;
    // });

  }

  @override
  void dispose() {
    //网络结束监听
    _netSubscription?.cancel();
    // _homePageWidgetSubscription?.cancel();
    _terminalNumRefreshSubscription?.cancel();
    _streamSubscription?.cancel();
    // _attendanceStreamSubscription.cancel();
    _returnPageStreamSubscription.cancel();
    // _viewModel?.topInfoValueNotifier?.removeListener(() { });

    _initPageNotifier?.dispose();
    homePageInterfaceEventMonitor.cancel();
    _terminalListViewModel.onDisposed();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _toScaffoldWidget();
  }

  @override
  void didChangeDependencies() {
    _user = UserRepository.getInstance().of(context);
    super.didChangeDependencies();
  }

  Widget _toScaffoldWidget() {
    return Scaffold(
      // backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: _toMainColumnWidget(),
    );
  }

  //顶部公司和Logo
  Widget _toIndexTopCompanyAndLogoWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.indexTopBaseValueNotifier,
      builder: (BuildContext context, IndexTopBaseInfo topBaseInfo, Widget child) {
        // baseInfo = topBaseInfo;
        return IndexTopCompanyAndLogoWidget(
          user: _user,
          // topInfo: topInfo,
          baseInfo: topBaseInfo,
          isShowTips: isShowTips,
          defaultgps: _latestGps,
          onTapTips: () {
            _setTips();
          },
          onScanResult: (){
            // _viewModel?.getPunchAndTerminalInfo(0, gps: _latestGps);
            _viewModel.getHomeTerminalInfo(0, gps: _latestGps);

          },
        );
      },
    );
  }

  //统计卡片
  Widget _toIndexStatisticsCardWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.indexTopPunchInfoValueNotifier,
      builder: (BuildContext context, PVCntBean topPunchInfo, Widget child){
        // punchInfo = topPunchInfo;
        print("卡片：" + topPunchInfo?.toJson().toString());
        return IndexStatisticsCardWidget(
          punchInfo: topPunchInfo,
        );
      },
    );
  }
  //管理终端
  Widget _toIndexManageTerminalBarWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.bindTermainalInfoValueNotifier,
        builder: (BuildContext context, IndexBindTermainalInfo topInfo, Widget child) {
          _topInfo = topInfo;
          return IndexManageTerminalBarWidget(
            topInfo: topInfo,
            gps: _latestGps,
          );
        }
    );
  }

  //播放列表
  Widget _playListWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.bindTermainalInfoValueNotifier,
        builder: (BuildContext context, IndexBindTermainalInfo topInfo, Widget child) {
          _topInfo = topInfo;
          SharePreferenceUtil.putString(SP_ALL_TERMINAL_HSNS, _getHsns(_topInfo?.data?.bindTerminalList));
          return judgeTerminalState(topInfo) ?IndexGuidanceNotesWidget(topInfo:topInfo,viewModel :_viewModel,gps: _latestGps,): Expanded(child: _contentDisplay(topInfo));
        }
    );
  }

  Widget _toMainColumnWidget() {
    // return ValueListenableBuilder(
    //   valueListenable: _viewModel?.bindTermainalInfoValueNotifier,
    //   builder:
    //       (BuildContext context, IndexBindTermainalInfo topInfo, Widget child) {
    //     // Map map = json.decode(json.encode(topInfo));
    //     _topInfo = topInfo;
    int urgentWidth = VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId())?208:161;
    return Stack(
      children: [
        Column(
          children: <Widget>[
            SizedBox(height: ScreenUtils.getStatusBarH(context)),
            _toNetworkStatusWidget(),
            ///顶部公司和Logo
            _toIndexTopCompanyAndLogoWidget(),
            Visibility(
                visible: UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition(),
                child: SizedBox(height: 15)
            ),
            // IndexTopCompanyAndLogoWidget(
            //   user: _user,
            //   // topInfo: topInfo,
            //   baseInfo: baseInfo,
            //   isShowTips: isShowTips,
            //   onTapTips: () {
            //     _setTips();
            //   },
            // ),

            ///统计卡片
            Visibility(
              visible: UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition(),
              child: Stack(
                children: [
                  _toIndexStatisticsCardWidget(),
                  // if(topInfo?.isShow ?? false)
                  _defaultLoadingCustomWidget()
                ],
              ),
            ),
            Visibility(
                visible: UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition(),
                child: SizedBox(height: 10)
            ),

            ///管理终端
            _toIndexManageTerminalBarWidget(),
            // IndexManageTerminalBarWidget(
            //   topInfo: topInfo,
            //   gps: _gps,
            // ),
            // IndexGuidanceNotesWidget(topInfo:topInfo,viewModel :_viewModel),
            _playListWidget(),
          ],
        ),
        // Center(
        //   child: MaterialClassicHeader(
        //     backgroundColor:Color(0xFF011c3a),
        //     color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        //   ),
        // ),
        Positioned(
          left: (ScreenUtils.getInstance().screenWidth - urgentWidth)/2,
          bottom: NAV_HEIGHT + 20 + ScreenUtils.getStatusBarH(context),
          child: _toUrgentModeWidget(),
        ),
      ],
    );
    //   },
    // );
  }

  Widget _defaultLoadingCustomWidget() {
    //开始倒计时
    // _value = 0;
    // if( _value<10){
    //   startCountdownTimer();
    // }
    // if(_value>10){
    //   showLoad = false;
    // }
    // showLoad = false;
    return Positioned(
      top: 20,
      left: (VgToolUtils.getScreenWidth()/2)-17.5,
      child: Visibility(
        // offstage: _value>10,
        visible: showLoad??false,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(32.5),
          child: Stack(
            children: [
              Container(
                  width: 35,
                  height: 35,
                  color: Color(0xFF011c3a).withOpacity(0.5)
              ),
              Positioned(
                top: 10,
                right: 10,
                child: Container(
                  width: 15,
                  height: 15,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    // valueColor:ColorTween(begin: Colors.white, end: Colors.red[900]).animate(null),
                    // backgroundColor:(topInfo?.PVCnt?.punchcnt ?? 0)==0? Colors.transparent: Colors.white,
                    // value: _value/190,
                  ),
                ),
              )
            ],

          ),
        ),
      ),
    );
  }

  // Widget _buildRefreshWidget() {
  //   return MaterialClassicHeader(
  //     backgroundColor:Color(0xFF011c3a),
  //     color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
  //   );
  // }


// 倒计时
//   void startCountdownTimer() {
//     if(_timer != null){
//       _timer.cancel();
//       _timer = null;
//     }
//     // 50毫秒执行一次
//     const oneSec = const Duration(milliseconds: 50);
//
//     var callback = (timer) => {
//       setState(() {
//         if (_value > 10) {
//           _timer.cancel();
//         } else {
//           _value = _value + 1;
//         }
//       })
//     };
//     _timer = Timer.periodic(oneSec, callback);
//
//   }


  /// 请求客户端
  Future<bool> checkNetwork()async{
    final dio = Dio();
    try {
      Response response = await dio.get(
        "http://123.207.32.32:8000/api/v1/recommend",
      );
      if (response.statusCode == HttpStatus.ok) {
        return true;
      } else {
        return false;
      }
    } on SocketException catch (_) {
      return false;
    }catch(exception){
      return false;
    }
  }

  ///弱网显示
  Widget _toNetworkStatusWidget(){
    return FutureBuilder(
        future: (Connectivity().checkConnectivity()),
        builder: (context, snapshot) {
          ConnectivityResult result;
          if (snapshot.connectionState == ConnectionState.done) {
            result = snapshot.data;
          }
          return StreamBuilder(
            stream: Connectivity().onConnectivityChanged,
            builder: (context,  snapshot) {
              if(snapshot.connectionState == ConnectionState.active){
                result = snapshot.data;
              }
              return FutureBuilder(
                future: checkNetwork(),
                builder: (context, connectState){
                  print("result:" + result.toString());
                  print("connectState?.data:" + (connectState?.data??true).toString());
                  return Visibility(
                    visible: (ConnectivityResult.none == result || !(connectState?.data??true)),
                    child: Container(
                      color: Color(0x33F95355),
                      height: 40,
                      child: Row(
                        children: [
                          SizedBox(width: 15,),
                          Image.asset(
                            "images/icon_tip_red.png",
                            width: 16,
                            height: 16,
                          ),
                          SizedBox(width: 6,),
                          Text(
                            "当前网络不可用，请检查你的网络",
                            style: TextStyle(
                              fontSize: 13,
                              color: Color(0xFFF95355),
                            ),
                          ),
                          Spacer(),
                          GestureDetector(
                            behavior: HitTestBehavior.translucent,
                            onTap: (){
                              // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
                              // _viewModel.getHomeBaseInfo();
                              _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
                              _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "当前网络不可用，请检查你的网络 onTap");
                              _viewModel.getUrgent();
                            },
                            child: Container(
                              width: 50,
                              alignment: Alignment.center,
                              child: Text(
                                "刷新",
                                style: TextStyle(
                                  fontSize: 11,
                                  color: Color(0xFFBFC2CC),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              );

            },
          );
        }
    );


  }

  ///显示屏网络不佳提示
  Widget _toTerminalUpdatePlayListStatusWidget(NewBindTerminalListBean listBean){
    String days;
    if(listBean.getTerminalIsOff()){
      if(StringUtils.isNotEmpty(listBean?.reportHsnLastTime??"")) {
        String currentTimeStr = DateUtil.getNowDateStr();
        int currentTime = DateTime.parse(currentTimeStr).millisecondsSinceEpoch;
        int time = DateTime.parse(listBean?.reportHsnLastTime).millisecondsSinceEpoch;
        int interval = (currentTime - time) ~/ (24 * 60 * 60 * 1000);
        if (interval > 2) {
          days = "已关机${interval}天";
        }else{
          days = "已关机";
        }
      }else{
        days = "已关机";
      }
      return Container(
        alignment: Alignment.centerLeft,
        margin: EdgeInsets.only(bottom: 11),
        height: 30,
        padding: EdgeInsets.only(left: 15, right: 15),
        decoration: BoxDecoration(
          color: Color(0x33F95355),
        ),
        child: Text(
          "${listBean?.getTerminalName()??"当前设备"}：${days}",
          style: TextStyle(
              fontSize: 12,
              color: ThemeRepository.getInstance().getMinorRedColor_F95355()
          ),
        ),
      );
    }
    return (("00" != _showTerminalStatus) && (_hintHsn == (listBean?.hsn??"")))?
    Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(bottom: 11),
      height: 30,
      padding: EdgeInsets.only(left: 15, right: 15),
      decoration: BoxDecoration(
        color: Color(0x33F95355),
      ),
      child: Text(
        "注：当前显示屏网络状况不佳，播控数据指令未完全同步",
        style: TextStyle(
            fontSize: 12,
            color: ThemeRepository.getInstance().getMinorRedColor_F95355()
        ),
      ),
    ): SizedBox();
  }

  ///紧急通告模式
  Widget _toUrgentModeWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.urgentValueNotifier,
      builder: (BuildContext context, MediaUrgentResponseBean bean, Widget child){
        if((bean?.data?.list??null) != null && bean.data.list.length > 0){
          return _toUrgentHintWidget(bean.data.list[0].id);
        }else{
          return SizedBox();
        }
      },
    );
  }

  ///紧急通告模式bubble
  Widget _toUrgentHintWidget(String picid){
    return Container(
      alignment: Alignment.center,
      height: 40,
      width: VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId())?208:161,
      padding: EdgeInsets.only(left: 16, right: 9),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(22.5),
        color: Color(0xE6BE0000),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Image.asset(
            "images/icon_open_urgent.png",
            width: 20,
          ),
          SizedBox(width: 6,),
          Text(
            "紧急通告模式",
            style: TextStyle(
              fontSize: 15,
              color: Colors.white,
              fontWeight: FontWeight.w600,
            ),
          ),
          Visibility(
              visible: VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId()),
              child: SizedBox(width: 20,)
          ),
          Visibility(
            visible: VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId()),
            child: Container(
              width: 47,
              height: 22,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(11),
                color: Color(0x66FFFFFF),
              ),
              child: GestureDetector(
                onTap: (){
                  _urgentViewModel.cancelSetPicUrgent(picid);
                },
                child: Text(
                  "关闭",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  bool judgeTerminalState(IndexBindTermainalInfo topInfo){
    //是否有新终端
    int _newTerminalCnt = topInfo?.data?.newTerminalCnt ?? 0;
    //终端列表是否有数据
    int _bindTerminalList = topInfo?.data?.bindTerminalList?.length ?? 0;

    //终端列表咩有数据
    if(_bindTerminalList==0){
      return true;
    }
    //有新终端
    // if(_newTerminalCnt !=0 ){
    //   return true;
    // }
    return false;
  }

  Widget _contentDisplay(IndexBindTermainalInfo topInfo) {
    return VgPlaceHolderStatusWidget(
      emptyStatus:
      topInfo?.data?.bindTerminalList == null || topInfo?.data.bindTerminalList.isEmpty,
      // emptyOnClick: () => _viewModel?.getTopInfoHttp(_selectedIndex),
      emptyOnClick: ()=>_viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps),
      // child: Column(
      //   children: <Widget>[
      //     _judgeTerminalDisplay(topInfo),
      //     SizedBox(
      //       height: 4,
      //     ),
      //     _getPlayList(topInfo),
      //   ],
      // ),
      child: ScrollConfiguration(
        behavior: MyBehavior(),
        child: NestedScrollView(
          physics: BouncingScrollPhysics(),
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [
              SliverToBoxAdapter(
                child: _judgeTerminalDisplay(topInfo),
              ),
            ];
          },
          body: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                SizedBox(
                  height: 4,
                ),
                _getPlayList(topInfo),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _judgeTerminalDisplay(IndexBindTermainalInfo topInfo) {
    if(_selectedIndex != _initPageNotifier?.value){
      _initPageNotifier?.value = _selectedIndex;
    }
    return Container(
//      height: topInfo == null || topInfo?.bindTerminalList == null
//          ? (ScreenUtils.screenW(context) - 30) / 2 - 8 + 12 + 4
//          : (topInfo.bindTerminalList.length <= 2
//              ? (ScreenUtils.screenW(context) - 30 - 8) / 2 + 12
//              : (ScreenUtils.screenW(context) - 15 - 16) / 2.5 + 12),
      height: ((ScreenUtils.screenW(context) - 15 - 16) / 2.5 + 12),
      child: IndexGridTerminalWidget(
        list: topInfo?.data?.bindTerminalList,
        selectIndex: _selectedIndex,
        onSelect: (index) {
          //更换今日播放内容
          String hsn = topInfo?.data?.bindTerminalList[index].hsn;
          _viewModel.getTerminalDetail(hsn);
          setState(() {
            _hintHsn = hsn;
            _selectedIndex = index;
            _showTerminalStatus = "00";
          });
          if(_horizontalController != null && _horizontalController.hasClients){
            _horizontalController.jumpTo(0);
          }
        },
        cancelRepeat: _onCancelRepeatByTerminal,
        selectValue: _initPageNotifier,
        onOff: _onOff,
        // setVolume: _setVolume,
      ),
    );
  }

  int _getIndex(TerminalDetailListItemBean itemBean){

    int index = 0;
    for(int i = 0; i < _terminalDetailResponseBean.data.list.length; i++){
      TerminalDetailListItemBean temp = _terminalDetailResponseBean.data.list[i];
      if(itemBean.isIndex() && (itemBean.buildingIndexId == temp.buildingIndexId)){
        index = i;
        break;
      }else if(itemBean.isSmart() && (itemBean.rasid == temp.rasid)){
        index = i;
        break;
      } else{
        if((itemBean?.picid??"-1") == temp.picid){
          index = i;
          break;
        }
      }
    }
    return index;
  }

  _onRepeat(TerminalDetailListItemBean itemBean) {
    // if (StringUtils.isEmpty(itemBean?.picid)) {
    //   VgToastUtils.toast(context, "资源获取失败");
    //   return;
    // }
    int index = _getIndex(itemBean);
    _terminalDetailResponseBean.data.list.forEach((element) {
      //如果此次操作是设置重复，那么要将原来的数据都置为不重复，防止两个重复标出现的状况
      element.stopflg = "00";
    });
    if("01" == itemBean.stopflg){
      itemBean.stopflg = "00";
    }else{
      itemBean.stopflg = "01";
    }
    _terminalDetailResponseBean.data.list[index] = itemBean;
    _viewModel.detailValueNotifier.value = _terminalDetailResponseBean;
    String detailCacheKey = NetApi.TERMINAL_PLAY_LIST_API + UserRepository.getInstance().authId ?? ""
        + itemBean.hsn ?? "";

    SharePreferenceUtil.putString(detailCacheKey, json.encode(_terminalDetailResponseBean));

    _topInfo?.data?.bindTerminalList?.forEach((element) {
      if(itemBean.hsn == element.hsn){
        if("01" == element.stopflg){
          element.stopflg = "00";
        }else{
          element.stopflg = "01";
        }
        _viewModel.bindTermainalInfoValueNotifier.value = _topInfo;
        // IndexTopInfoResponseBean topInfoResponseBean = new IndexTopInfoResponseBean();
        // topInfoResponseBean.data = _topInfo;
        // topInfoResponseBean.success = true;
        // topInfoResponseBean.code = "200";
        // topInfoResponseBean.msg = "处理成功";
        SharePreferenceUtil.putString(_punchAndTerminalInfoCacheKey, json.encode(_topInfo));
      }
    });

    if(itemBean.isIndex()){
      _viewModel?.repeatBuildingIndex(context, itemBean.hsn, itemBean.buildingIndexId, itemBean.stopflg);
    }else if(itemBean.isSmart()){
      _viewModel?.repeatSmartHome(context, itemBean.hsn, itemBean.rasid, itemBean.stopflg);
    }else{
      _viewModel?.repeatPlay(context, itemBean.picid, itemBean.editStopFlg,
          itemBean.id, itemBean.hsn);
    }
  }

  // _setVolume(String hsn, String onOff, int volume){
  //   if (StringUtils.isEmpty(hsn)) {
  //     VgToastUtils.toast(context, "设备信息异常");
  //     return;
  //   }
  //   VgEventBus.global.send(new HomePageInterfaceEventMonitor());
  //   _viewModel?.changeVolume(context, hsn, onOff, volume, _selectedIndex);
  // }

  _onOff(bool offStatus, String hsn, int id, String terminalName, ComAutoSwitchBean autoBean) async{
    SetTerminalStatusMenuDialog.navigatorPushDialog(context,
          (currentState){
        _terminalListViewModel.terminalOffScreen(context, hsn, "00", callback: (){
        });
      },
          (currentState){
        _terminalListViewModel.terminalOffScreen(context, hsn, "01", callback: (){
        });
      },
          (currentState){
        _terminalListViewModel.terminalOff(context, hsn, callback: (){
        });
      },
          (time){

      },
      offStatus?SetTerminalStateType.off:SetTerminalStateType.open,
      "",
      "",
      hsn,
      id,
      terminalName,
      "",
      autoBean,
    );

    // if(offStatus){
    //   //当前是关机，执行开机
    //   bool result =
    //   await CommonConfirmCancelDialog.navigatorPushDialog(context,
    //       title: "提示",
    //       content: "确定开启该设备？",
    //       cancelText: "取消",
    //       confirmText: "开启",
    //       confirmBgColor: ThemeRepository.getInstance()
    //           .getHintGreenColor_00C6C4());
    //   if(result??false){
    //     RouterUtils.pop(context);
    //     _terminalListViewModel.terminalOffScreen(context, hsn, "00");
    //   }
    // }else{
    //   //当前是开机，执行关机
    //   print("执行关机");
    //   bool result =
    //       await CommonConfirmCancelDialog.navigatorPushDialog(context,
    //       title: "提示",
    //       content: "确定关闭该设备？",
    //       cancelText: "取消",
    //       confirmText: "关闭",
    //       confirmBgColor: ThemeRepository.getInstance()
    //           .getMinorRedColor_F95355(),);
    //   if (result ?? false) {
    //     _terminalListViewModel.terminalOff(context, hsn);
    //   }
    // }
  }

  _onCancelRepeatByTerminal(String hsn) {
    if (StringUtils.isEmpty(hsn)) {
      VgToastUtils.toast(context, "设备信息异常");
      return;
    }
    _topInfo?.data?.bindTerminalList?.forEach((element) {
      if(hsn == element.hsn){
        element.stopflg = "00";
      }
    });
    _viewModel.bindTermainalInfoValueNotifier.value = _topInfo;
    SharePreferenceUtil.putString(_punchAndTerminalInfoCacheKey, json.encode(_topInfo));
    if(hsn == _terminalDetailResponseBean.data.hsnMap.hsn){
      for(int i = 0; i < _terminalDetailResponseBean.data.list.length; i++){
        if("00" != _terminalDetailResponseBean.data.list[i].stopflg){
          _terminalDetailResponseBean.data.list[i].stopflg = "00";
          _viewModel.detailValueNotifier.value = _terminalDetailResponseBean;
          String detailCacheKey = NetApi.TERMINAL_PLAY_LIST_API + UserRepository.getInstance().authId ?? ""
              + hsn ?? "";
          SharePreferenceUtil.putString(detailCacheKey, json.encode(_terminalDetailResponseBean));
          break;
        }
      }
    }
    _viewModel?.cancelRepeatPlayByHsn(context, hsn);
  }

  String _getHsns(List<NewBindTerminalListBean> list){
    if(list == null || list.isEmpty){
      return "";
    }
    return list.map((e) => e.hsn).toList().join(",");
  }

  Widget _getPlayList(IndexBindTermainalInfo topInfo) {
    return ValueListenableBuilder(
      valueListenable: _viewModel?.detailValueNotifier,
      builder: (BuildContext context,
          TerminalDetailResponseBean detailResponseBean, Widget child) {
        Map map = json.decode(json.encode(detailResponseBean));
        _terminalDetailResponseBean = TerminalDetailResponseBean.fromMap(map, isCache: true);

        if(topInfo != null && topInfo.data.bindTerminalList != null && _selectedIndex >= topInfo.data.bindTerminalList.length){
          _selectedIndex = 0;
          _initPageNotifier?.value = _selectedIndex;
          // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
          // _viewModel.getHomeBaseInfo();
          _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
          _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "_getPlayList");
        }
        NewBindTerminalListBean listBean = topInfo.data?.bindTerminalList[_selectedIndex];
        return Container(
          // color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          child: Column(
            children: <Widget>[
              //今日播放
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  if(UserRepository.getInstance().isSmartHomeCompany()){
                    return;
                  }
                  NewBindTerminalListBean listBean = topInfo.data?.bindTerminalList[_selectedIndex];
                  SingleTerminalMangePage.navigatorPush(
                    context,
                    listBean.hsn,
                    _getHsns(topInfo.data?.bindTerminalList),
                    listBean?.getTerminalName(),
                    listBean?.branchname,
                    listBean?.cbid,
                    listBean.getTerminalState(), listBean.rcaid,
                    onOffTime: listBean.autoOnoffTime,
                    onOffWeek: listBean.autoOnoffWeek,
                    autoOnOff: listBean?.autoOnoff,
                    autoBean: listBean?.comAutoSwitch,
                  );
                },
                child: Container(
                  height: 50,
                  margin: EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                    children: <Widget>[
                      Text(
                        "今日播放文件·${(detailResponseBean?.data?.list?.length??0)}",
                        style: TextStyle(
                          fontSize: 14,
                          color: ThemeRepository.getInstance()
                              .getTextMainColor_D0E0F7(),
                        ),
                      ),
                      Spacer(),
                      Visibility(
                        visible: !UserRepository.getInstance().isSmartHomeCompany(),
                        child: Row(
                          children: <Widget>[
                            Image.asset(
                              "images/icon_add_pic.png",
                              width: 11,
                              color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                            ),
                            SizedBox(width: 3,),
                            Text(
                              "添加",
                              style: TextStyle(
                                color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                                fontSize: 14,
                              ),
                            ),
                            // Text(
                            //   detailResponseBean == null
                            //       ? ""
                            //       : "共" +
                            //       detailResponseBean.data.list.length
                            //           .toString() +
                            //       "文件",
                            //   style: TextStyle(
                            //     color: ThemeRepository.getInstance()
                            //         .getDefaultGrayColor_FF5E687C(),
                            //     fontSize: 12,
                            //     height: 1.2,
                            //   ),
                            // ),
                            // SizedBox(
                            //   width: 8,
                            // ),
                            // Image.asset(
                            //   "images/index_arrow_ico.png",
                            //   width: 6,
                            // )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              _toTerminalUpdatePlayListStatusWidget(listBean),
              true
                  ? _getHorizontalList(
                  detailResponseBean?.data?.list ?? null, topInfo ?? null)
                  : _getVerticalList(detailResponseBean?.data?.list ?? null,
                  topInfo ?? null),
              SizedBox(height: 20,)
            ],
          ),
        );
      },
    );
  }

  Widget _getHorizontalList(List<TerminalDetailListItemBean> terminalList,
      IndexBindTermainalInfo topInfo) {
    // if(topInfo != null && topInfo.bindTerminalList != null && _selectedIndex >= topInfo.bindTerminalList.length){
    //     _selectedIndex = 0;
    //     _initPageNotifier?.value = _selectedIndex;
    //     _viewModel.getTopInfoHttp(_selectedIndex);
    // }
    String hsn = (topInfo == null)?"" : topInfo.data.bindTerminalList[_selectedIndex].hsn;
    String terminalName = (topInfo == null)? "" : topInfo.data.bindTerminalList[_selectedIndex].terminalName;
    bool isOff = (topInfo == null)? false : topInfo.data.bindTerminalList[_selectedIndex].getTerminalIsOff();
    String position = (topInfo == null)? "" : topInfo.data.bindTerminalList[_selectedIndex].branchname;
    String cbid = (topInfo == null)? "" : topInfo.data.bindTerminalList[_selectedIndex].cbid;
    return Container(
      height: ((ScreenUtils.screenW(context) - 15 - 16) / 2.5) * 244 / 137,
      child: IndexHorizontalVerticalPlayListWidget(
        list: terminalList,
        direction: 0,
        hsn:_hintHsn,
        initOffSet: 0.0,
        controller: _horizontalController,
        onRepeat: _onRepeat,
        terminalName: terminalName,
        isOff: isOff,
        // position: _terminalDetailResponseBean?.data?.hsnMap?.position??"",
        position: position??"",
        cbid: cbid??"",
      ),
    );
  }


  Widget _getVerticalList(List<TerminalDetailListItemBean> terminalList,
      IndexBindTermainalInfo topInfo) {
    return Expanded(
        child: IndexHorizontalVerticalPlayListWidget(
          list: terminalList,
          direction: 1,
          initOffSet: 0.0,
        ));
  }

  void _getSPValue() {
    _getTips().then((value) {
      isShowTips = value ?? true;
    });
    setState(() {});
  }

  ///设置缓存提示
  void _setTips() {
    if (isShowTips == false) {
      return;
    }
    SharePreferenceUtil.putBool(
        UserRepository.getInstance().userData?.user?.loginphone, false);
    isShowTips = false;
    setState(() {});
  }

  ///获取提示缓存
  Future<bool> _getTips() {
    return SharePreferenceUtil.getBool(
        UserRepository.getInstance().userData?.user?.loginphone);
  }

  /// 定位权限
  Future<String> requestLocation() async {
    PermissionStatus locationPermission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.location);
    if (locationPermission == PermissionStatus.granted) {
      return "";
    } else {
      Map<PermissionGroup, PermissionStatus> permissions =
      await PermissionHandler().requestPermissions([
        PermissionGroup.location,
      ]);
      bool give =
          permissions[PermissionGroup.location] == PermissionStatus.granted;
      if(give){
        return "";
      }else {
        return "请在设置界面给予App定位权限";
      }
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: //从后台切换前台，界面可见
      // Future<String> permissionResult = requestLocation();
      // permissionResult.then((value) {
      //   if(StringUtils.isEmpty(value)){
      //     VgLocation().requestSingleLocation((value) {
      //       print("回到前台，请求更新位置");
      //     });
      //   }
      // });
        VgLocation().requestSingleLocationWithoutCheckPermission((value){
          print("回到前台，请求更新位置");
        });
        connectivityInitState();
        // _viewModel.getPunchAndTerminalInfo(_selectedIndex, gps: _latestGps);
        // _viewModel.getHomeBaseInfo();
        _viewModel.getHomeTerminalInfo(_selectedIndex, gps: _latestGps);
        _viewModel.getHomeCompanyBaseInfoAndPunchInfoFromNet(from: "回到前台");
        _viewModel?.getUrgent();
        VgEventBus.global.send(AppRefreshEvent());
        break;
      case AppLifecycleState.paused: // 界面不可见，后台
        break;
      case AppLifecycleState.detached: // APP结束时调用
        break;
    }
  }
}
